package com.bnz.springboot.config;


import com.alibaba.druid.pool.DruidDataSource;

import com.bnz.springboot.properties.JdbcProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;


@Configuration           //相当于applicationContext文件
//读取指定属性文件， 相当于： <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
@PropertySource("classpath:properties/db.properties")
public class MyConfig {

    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //为数据源赋值方法一
    @Bean     //相当于<bean id="druidDataSource">
    public DruidDataSource druidDataSource(){

        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;

    }

    //方法二
    /*@Bean
    public DruidDataSource dataSource(JdbcProperties jdbc){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(jdbc.getDriverClassesName());
        druidDataSource.setUrl(jdbc.getUrl());
        druidDataSource.setUsername(jdbc.getUsername());
        druidDataSource.setPassword(jdbc.getPassword());

        return druidDataSource;
    }*/

    //方法三
    /*@Bean
    @ConfigurationProperties(prefix = "jdbc") //读取默认配置文件applicontext.properties/yml
    public DruidDataSource druidDataSource(){
        //此时，将appliction.properties文件中的jdbc前缀去掉后，就是dirverClassName/url/username/password,将其值赋给druidDatasource这个对象的对应属性
        DruidDataSource druidDataSource=new DruidDataSource();
        return druidDataSource;
    }*/


}
